<?php

namespace App\Exports;

use App\Models\Order;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithProperties;

class OrderExport implements FromQuery, WithHeadings, WithProperties, WithMapping
{
	use Exportable;
	
    public function query()
    {
    	return Order::query()
		    ->unclosed()
		    ->uncancelled()
		    ->undelivered()
		    ->doesntHave('refunds')
		    ->orderByDesc('id');
    }
    
    public function headings(): array
    {
    	return [
		    '平台',
		    '订单ID',
		    '订单编号',
		    '物流公司',
		    '物流单号',
		    
		    '订单供货',
		    '商品标题',
		    'SKU名称',
		    'SKU货号',
		    'SKU规格',
		    'SKU成本',
		    'SKU数量',
		    '收货客户',
		    '收货电话',
		    '收货地址',
		    '下单时间',
		    '付款时间',
	    ];
    }
    
    public function properties(): array
    {
    	return [
		    'id'                        => '订单ID',
		    'number'                    => '订单编号',
		    'order.delivery_company'    => '物流公司',
		    'order.delivery_number'     => '物流单号',
		    
		    'vendor_id'                 => '订单供货',
		    'product_id'                => '商品标题',
		    'order.items.sku_name'      => 'SKU名称',
		    'order.items.sku_code'      => 'SKU货号',
		    'order.items.sku_attr'      => 'SKU规格',
		    'order.items.cost'          => 'SKU成本',
		    'order.items.amount'        => 'SKU数量',
		    'order.contact_name'        => '收货客户',
		    'order.contact_phone'       => '收货电话',
		    'order.contact_address'     => '收货地址',
		    'created_at'                => '下单时间',
		    'paid_at'                   => '付款时间',
	    ];
    }
    
    public function map($order): array
    {
    	$from = '有点东西';
    	$item = $order->items->first();
    	$vendorName = isset($item->vendor) ? $item->vendor->name : '';
    	$skuCode = isset($item->sku) ? $item->sku->code : '';
    	$skuAttrValue = empty($item->sku_attr_value) ? '' : $item->sku_attr_value[0];
    	$orderPaidAt = $order->paid_at ? $order->paid_at->toDatetimeString() : '';
    	$orderCreatedAt = $order->created_at ? $order->created_at->toDatetimeString() : '';
    	
	    $data = [
	    	$from,
		    $order->id,
		    $order->number,
		    $order->delivery_company ?? '',
		    $order->delivery_number ?? '',
		    $vendorName,
		    $item->product_title,
		    $item->sku_name,
		    $skuCode,
		    $skuAttrValue,
		    $item->cost,
		    $item->amount,
		    $order->address['contact_name'],
		    $order->address['contact_phone'],
		    $order->address['address'],
		    $orderPaidAt,
		    $orderCreatedAt,
	    ];
	    
	    return $data;
    }
}
